package edu.gxmzu.task.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import edu.gxmzu.task.entity.Attachments;
import edu.gxmzu.task.mapper.AttachmentsMapper;
import edu.gxmzu.task.mapper.WordMapper;
import edu.gxmzu.task.models.TaskBoardModel;
import edu.gxmzu.task.models.WorkModel;
import edu.gxmzu.task.params.SearchTaskParam;
import edu.gxmzu.task.params.UpdateAdminWorkParam;
import edu.gxmzu.task.params.UpdateUserWorkParam;
import edu.gxmzu.task.service.WordService;
import edu.gxmzu.task.utils.FileHashUtil;
import edu.gxmzu.task.utils.FileUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class WordServiceImpl implements WordService {

    private static final Logger logger = LoggerFactory.getLogger(TaskDisposeServiceImpl.class);
    @Resource
    private WordMapper wordMapper;

    @Resource
    private AttachmentsMapper attachmentsMapper;

    @Override
    public List<WorkModel> getWorkByUserId(Long userId) {
        return wordMapper.getWorkByUserId(userId);
    }


    @Override
    public int updateUserWork(UpdateUserWorkParam updateUserWorkParam) throws IOException {
        if(updateUserWorkParam.getFile() != null){
            Attachments attachments = uploadFile(updateUserWorkParam.getFile(),updateUserWorkParam.getAttachmentsId());
            if(updateUserWorkParam.getAttachmentsId() == null){
                attachments.setId(IdWorker.getIdStr());
                updateUserWorkParam.setAttachmentsId(attachments.getId());
                int y = wordMapper.insertUserAttachment(attachments);
                if(y < 1){
                    return  0;
                }
            }else{
                attachments.setId(updateUserWorkParam.getAttachmentsId());
                int i = wordMapper.updateUserAttachment(attachments);
                if(i < 1){
                    return  0;
                }
            }

        }
         int x = wordMapper.updateUserWork(updateUserWorkParam);
         if(x > 0 ){
             return  1;
         }else {
             return 0;
         }
    }

    @Override
    public int updateAdminWork(UpdateAdminWorkParam updateAdminWorkParam) throws IOException {
        if(updateAdminWorkParam.getFile() != null){
            Attachments attachments = uploadFile(updateAdminWorkParam.getFile(),updateAdminWorkParam.getAttachmentsId());
            if(updateAdminWorkParam.getAttachmentsId() == null){
                attachments.setId(IdWorker.getIdStr());
                updateAdminWorkParam.setAttachmentsId(attachments.getId());
                int y = wordMapper.insertUserAttachment(attachments);
                if(y < 1){
                    return  0;
                }
            }else {
                attachments.setId(updateAdminWorkParam.getAttachmentsId());
                int i = wordMapper.updateUserAttachment(attachments);
                if(i < 1){
                    return  0;
                }
            }
        }
        int x = wordMapper.updateAdminWork(updateAdminWorkParam);
        if(x > 0 ){
            return  1;
        }else {
            return 0;
        }
    }

    @Override
    public TaskBoardModel getAllWorks(String userId) {
        return wordMapper.getAllWorks(userId);
    }

    @Override
    public List<WorkModel> SearchTask(SearchTaskParam searchTaskParam) {
        return wordMapper.SearchTask(searchTaskParam);
    }

    public Attachments uploadFile(MultipartFile file,String attachmentId) throws IOException {
        Attachments attachments = null;
        Map<String, Object> result = new HashMap<>();
        String originalFileName = file.getOriginalFilename();
        String algorithm = "SHA-256";       // 文件编码
        if (originalFileName == null || originalFileName.isEmpty()) {
            result.put("message", "File name is empty");
            throw new FileNotFoundException("找不到文件");
        }
        // 文件名
        String fileName = FileUtil.getFileName(originalFileName);
        // 文件类型
        String extension = FileUtil.getFileExtension(originalFileName);

        // 文件大小
        long size = file.getSize();

        String projectPath = System.getProperty("user.dir");
        String filesPath = projectPath + File.separator + "WEB-INF" + File.separator + "files";
        String filesRealPath = filesPath + File.separator + originalFileName;

        File saveFile = new File(filesRealPath);
        String newFileName = null;
        try {
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            if (saveFile.exists()) {
                // Create a unique filename
                newFileName = System.currentTimeMillis() + "_" + fileName + "." + extension;
                saveFile = new File(filesPath + File.separator + newFileName);
            }
            file.transferTo(saveFile);

            // 文件哈希值
            String fileHash = FileHashUtil.getFileHash(filesRealPath, algorithm);

            if(StringUtils.hasText(newFileName) &&
               StringUtils.hasText(fileHash) &&
               StringUtils.hasText(extension) &&
               StringUtils.hasText(String.valueOf(size)) &&
               StringUtils.hasText(filesRealPath)
            ){
                attachments = new Attachments(attachmentId,newFileName,fileHash,extension,size,filesRealPath);
                return attachments;
            }

        } catch (IOException | NoSuchAlgorithmException e) {
            logger.error("FileUploadController====>>>>upload====>>>Failed to upload file", e);
        }
        return attachments;
    }

}
